package com.fau.wmbj.server.controller;

import cn.hutool.core.io.FileUtil;
import com.alibaba.fastjson.JSONObject;
import com.fau.wmbj.server.config.CurrentUser;
import com.fau.wmbj.server.entity.User;
import com.fau.wmbj.server.idempotent.annotation.RepeatSubmit;
import com.fau.wmbj.server.storage.*;
import com.fau.wmbj.server.utils.Filter;
import com.fau.wmbj.server.utils.Message;
import com.fau.wmbj.server.utils.MimeTypeUtils;
import com.fau.wmbj.server.utils.StringUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.*;

/**
 * 文件
 */
@Slf4j
@RequiredArgsConstructor(onConstructor_ = {@Lazy, @Autowired})
@RestController("fileController")
@RequestMapping("/file")
public class FileController {

    private final StorageService storageService;
    private final StorageConfigService pluginService;
    private final StorageDirectoryService fileDetailService;

    /**
     * 上传
     */
    @RepeatSubmit
    @PostMapping(value = "/upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public Message uploadFile(@RequestPart("file") MultipartFile file, @CurrentUser User user) {
        if (!file.isEmpty()) {
            try {
                String avatar = storageService.upload(file);
                return Message.success("上传成功", avatar);
            } catch (Exception e) {
                log.error(e.getMessage(), e);
                return Message.error(e.getMessage());
            }
        }
        return Message.error("上传异常，请联系管理员");
    }

    /**
     * 图片上传
     */
    @RepeatSubmit
    @PostMapping(value = "/upload-image", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public Message uploadImage(@RequestPart("file") MultipartFile file, @CurrentUser User user) {
        if (!file.isEmpty()) {
            String extension = FileUtil.extName(file.getOriginalFilename());
            if (!StringUtils.equalsAnyIgnoreCase(extension, MimeTypeUtils.IMAGE_EXTENSION)) {
                return Message.error("文件格式不正确，请上传" + Arrays.toString(MimeTypeUtils.IMAGE_EXTENSION) + "格式");
            }
            try {
                String avatar = storageService.upload(file);
                return Message.success("上传成功", avatar);
            } catch (Exception e) {
                log.error(e.getMessage(), e);
                return Message.error(e.getMessage());
            }
        }
        return Message.error("上传图片异常，请联系管理员");
    }

    /**
     * 上传
     */
    @RepeatSubmit
    @PostMapping(value = "/upload-local", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    @ResponseBody
    public Message upload(MultipartFile file) {
        try {
            String s = storageService.uploadLocal(file).split("upload")[1];
            return Message.success(s);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return Message.error(e.getMessage());
        }
    }

    /**
     * 上传
     */
    @PostMapping("/delete")
    @ResponseBody
    public ResponseEntity<?> delete(String url) {
        try {
            String filePath = "E:\\upload" + url;
            File file = new File(filePath);
            if (file.exists()) {
                file.delete();
            }
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("result", "ok");
            return ResponseEntity.ok(jsonObject);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return ResponseEntity.badRequest().body(e.getMessage());
        }
    }

    /**
     * 上传
     */
    @PostMapping("/upload-base64")
    @ResponseBody
    public Message uploadBase64(String imgbase64, String imgType, String tableName, Long tableId) {
        StorageDirectory fileDetail;
        try {
            fileDetail = storageService.uploadBase64(imgType, imgbase64, tableName, tableId, false);
        } catch (IOException e) {
            log.error(e.getMessage(), e);
            return Message.error(e.getMessage());
        }
        if (fileDetail == null) {
            return Message.error("上传文件出现错误");
        }
        return Message.success(fileDetail);
    }


    /**
     * 分片上传文件
     */
    @PostMapping("/upload-chunk")
    @ResponseBody
    public Message uploadChunk(MultipartFile file, Boolean preview, String fileMd5, Integer chunk, Integer chunks, Integer chunkSize, Long tableId, String tableName) {
        try {
            if (chunk == null) {
                chunk = 0;
            }
            if (chunks == null) {
                chunks = 1;
            }
            return storageService.uploadChunk(file, preview, tableName, tableId, fileMd5, chunk, chunks, chunkSize, true);
        } catch (Exception e) {
            return Message.error(e.getMessage());
        }
    }


    /**
     * 删除文件
     */
    @PostMapping("/deleteImg")
    @ResponseBody
    public Message del(@RequestParam(value = "urls[]") String[] urls) {
        List<Storage> storagePlugins = pluginService.getStoragePlugins();
        for (Storage storagePlugin : storagePlugins) {
            if (storagePlugin.getIsEnabled()) {
                for (String url : urls) {
                    String groupId = "";
                    String storagePluginId = "";
                    storageService.delete(url, groupId, storagePluginId, false);
                }
            }
        }
        return Message.success();
    }

    /**
     *
     */
    @GetMapping("/gen-url")
    @ResponseBody
    public Map<String, Object> genUrl(@CurrentUser User user, String url, HttpServletResponse response) {
        Map<String, Object> res = new HashMap<>(16);
        String msg = "";
        String type = "";
        String url_ = "";
        if (user == null) {
            msg = "请登录后再试！";
            type = "error";
        } else {
            if (StringUtils.isNotBlank(url)) {
                String n1 = url.substring(url.lastIndexOf("/")).replace("/", "").split("\\?")[0];
                List<Filter> filters = new ArrayList<>();
                filters.add(Filter.like("url", "%" + n1 + "%"));
                List<StorageDirectory> list = fileDetailService.findList(1, filters, null);
                if (CollectionUtils.isNotEmpty(list)) {
                    url_ = storageService.getUrl(list.get(0), false, 60);
                    type = "success";
                    msg = "请求成功";
                } else {
                    msg = "文件不存在";
                    type = "error";
                }
            } else {
                msg = "url不能为空！";
                type = "error";
            }

        }
        res.put("msg", msg);
        res.put("type", type);
        res.put("url", url_);
        return res;
    }

    /**
     *
     */
    @GetMapping("/gen-url2")
    @ResponseBody
    public Map<String, Object> genUrl2(@CurrentUser User user, Long tableId, String tableName, HttpServletResponse response) {
        Map<String, Object> res = new HashMap<>(16);
        String msg = "";
        String type = "";
        List<String> urlList = new ArrayList<>();
        if (user == null) {
            msg = "请登录后再试！";
            type = "error";
        } else {
            if (StringUtils.isNotBlank(tableName) && tableId != null) {
                List<Filter> filters = new ArrayList<>();
                filters.add(Filter.eq("tableId", tableId));
                filters.add(Filter.eq("tableName", tableName));
                List<StorageDirectory> list = fileDetailService.findList(null, filters, null);
                if (CollectionUtils.isNotEmpty(list)) {
                    for (StorageDirectory fileDetail : list) {
                        String url_ = storageService.getUrl(fileDetail, false, 60);
                        urlList.add(url_);
                    }
                    type = "success";
                    msg = "请求成功";
                } else {
                    msg = "文件不存在";
                    type = "error";
                }
            } else {
                msg = "url不能为空！";
                type = "error";
            }

        }
        res.put("msg", msg);
        res.put("type", type);
        res.put("urlList", urlList);
        return res;
    }

    /**
     *
     */
    @PostMapping("/get-src")
    @ResponseBody
    public void del(@CurrentUser User user, String url, HttpServletResponse response) {
        try {
            PrintWriter writer = response.getWriter();
            writer.write(url);
            writer.flush();
            writer.close();
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        }
    }

}